<template>
  <el-container class="fm2-container">
    <el-main class="fm2-main">
      <el-container>
        <el-aside width="250px">
          <div class="components-list">
            <template v-if="basicFields.length">
              <div class="widget-cate">基础字段</div>
              <draggable
                tag="ul"
                :list="basicComponents"
                v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                :move="handleMove"
                @end="handleMoveEnd"
                @start="handleMoveStart"
              >

                <li v-for="(item, index) in basicComponents" v-if="basicFields.indexOf(item.type)>=0" :key="index" class="form-edit-widget-label" :class="{'no-put': item.type === 'divider'}">
                  <a>
                    <i class="icon iconfont" :class="item.icon" />
                    <span>{{ item.name }}</span>
                  </a>
                </li>
              </draggable>
            </template>

            <template v-if="advanceFields.length">
              <div class="widget-cate">高级字段</div>
              <draggable
                tag="ul"
                :list="advanceComponents"
                v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                :move="handleMove"
                @end="handleMoveEnd"
                @start="handleMoveStart"
              >

                <li v-for="(item, index) in advanceComponents" v-if="advanceFields.indexOf(item.type) >= 0" :key="index" class="form-edit-widget-label" :class="{'no-put': item.type === 'table'}">
                  <a>
                    <i class="icon iconfont" :class="item.icon" />
                    <span>{{ item.name }}</span>
                  </a>
                </li>
              </draggable>
            </template>

            <template v-if="layoutFields.length">
              <div class="widget-cate">布局字段</div>
              <draggable
                tag="ul"
                :list="layoutComponents"
                v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                :move="handleMove"
                @end="handleMoveEnd"
                @start="handleMoveStart"
              >

                <li v-for="(item, index) in layoutComponents" v-if="layoutFields.indexOf(item.type) >=0" :key="index" class="form-edit-widget-label no-put">
                  <a>
                    <i class="icon iconfont" :class="item.icon" />
                    <span>{{ item.name }}</span>
                  </a>
                </li>
              </draggable>
            </template>

          </div>

        </el-aside>
        <el-container class="center-container" direction="vertical">
          <el-header class="btn-bar" style="height: 45px;">
            <slot name="action" />
            <el-button v-if="clearable" type="text" size="medium" icon="el-icon-back" @click="handleBack">返回</el-button>
            <el-button v-if="generateJson" type="text" size="medium" icon="el-icon-circle-check" @click="handleSave">保存</el-button>
            <!--<el-button v-if="upload" type="text" size="medium" icon="el-icon-upload2" @click="handleUpload">导入json</el-button>-->
            <el-button v-if="generateJson" type="text" size="medium" icon="el-icon-tickets" @click="handleGenerateJson">生成json</el-button>
          <!--  <el-button v-if="generateCode" type="text" size="medium" icon="el-icon-document" @click="handleGenerateCode">生成代码</el-button>-->
            <el-button v-if="clearable" type="text" size="medium" icon="el-icon-delete" @click="handleClear">清空</el-button>
            <el-button v-if="preview" type="text" size="medium" icon="el-icon-view" @click="handlePreview">预览</el-button>
          </el-header>
          <el-main id="view-container" :class="{'widget-empty': widgetForm.list.length === 0}">

            <widget-form v-if="!resetJson" ref="widgetForm" :data="widgetForm" :select.sync="widgetFormSelect" />
          </el-main>
        </el-container>

        <el-aside class="widget-config-container">
          <el-container>
            <el-header height="45px">
              <div class="config-tab" :class="{active: configTab==='widget'}" @click="handleConfigSelect('widget')">字段属性</div>
              <div class="config-tab" :class="{active: configTab==='form'}" @click="handleConfigSelect('form')">表单属性</div>
            </el-header>
            <el-main class="config-content">
              <widget-config v-show="configTab==='widget'" :data="widgetFormSelect" :all="widgetForm.list" />
              <form-config v-show="configTab==='form'" :data="widgetForm.config" />
            </el-main>
          </el-container>

        </el-aside>

        <cus-dialog
          ref="widgetPreview"
          :visible="previewVisible"
          width="1000px"
          form
          @on-close="previewVisible = false"
        >
          <generate-form v-if="previewVisible" ref="generateForm" insite="true" :data="widgetForm" :value="widgetModels" @on-change="handleDataChange">

            <template v-slot:blank="scope">
              Width <el-input v-model="scope.model.blank.width" style="width: 100px" />
              Height <el-input v-model="scope.model.blank.height" style="width: 100px" />
            </template>
          </generate-form>

          <template slot="action">
            <!-- <el-button type="primary" @click="handleTest">获取数据</el-button>-->
            <el-button @click="handleReset">重置</el-button>
          </template>
        </cus-dialog>

        <cus-dialog
          ref="jsonPreview"
          :visible="jsonVisible"
          width="800px"
          form
          @on-close="jsonVisible = false"
        >

          <div id="jsoneditor" style="height: 400px;width: 100%;">{{ jsonTemplate }}</div>

          <template slot="action">
            <el-button type="primary" class="json-btn" :data-clipboard-text="jsonCopyValue">复制数据</el-button>
          </template>
        </cus-dialog>

        <cus-dialog
          ref="uploadJson"
          :visible="uploadVisible"
          width="800px"
          form
          @on-close="uploadVisible = false"
          @on-submit="handleUploadJson"
        >
          <el-alert type="info" title="JSON格式如下，直接复制生成的json覆盖此处代码点击确定即可" />
          <div id="uploadeditor" style="height: 400px;width: 100%;">{{ jsonEg }}</div>
        </cus-dialog>

        <cus-dialog
          ref="codePreview"
          :visible="codeVisible"
          width="800px"
          form
          :action="false"
          @on-close="codeVisible = false"
        >
          <!-- <div id="codeeditor" style="height: 500px; width: 100%;">{{htmlTemplate}}</div> -->
          <el-tabs v-model="codeActiveName" type="border-card" style="box-shadow: none;">
            <el-tab-pane label="Vue Component" name="vue">
              <div id="vuecodeeditor" style="height: 500px; width: 100%;">{{ vueTemplate }}</div>
            </el-tab-pane>
            <el-tab-pane label="HTML" name="html">
              <div id="codeeditor" style="height: 500px; width: 100%;">{{ htmlTemplate }}</div>
            </el-tab-pane>
          </el-tabs>
        </cus-dialog>
      </el-container>
    </el-main>
    <el-dialog title="页面信息" :visible.sync="saveDialogVisible">
      <el-form ref="viewDesignForm" :model="viewDesign" :rules="rules" size="mini">
        <el-form-item label="页面名称" prop="viewName" :label-width="formLabelWidth">
          <el-input v-model="viewDesign.viewName" autocomplete="off" placeholder="请填写页面名称" />
        </el-form-item>
        <el-form-item label="页面描述" prop="description" :label-width="formLabelWidth">
          <el-input v-model="viewDesign.description" type="textarea" autocomplete="off" placeholder="请填写页面描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="saveDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
import Draggable from 'vuedraggable'
import WidgetConfig from './WidgetConfig'
import FormConfig from './FormConfig'
import WidgetForm from './WidgetForm'
import CusDialog from './CusDialog'
import GenerateForm from './GenerateForm'
import Clipboard from 'clipboard'
import { basicComponents, layoutComponents, advanceComponents } from './componentsConfig.js'
import generateCode from './generateCode.js'
import { get, save, update } from '@/api/developer/ViewDesign'

export default {
  name: 'FmMakingForm',
  components: {
    Draggable,
    WidgetConfig,
    FormConfig,
    WidgetForm,
    CusDialog,
    GenerateForm
  },
  props: {
    preview: {
      type: Boolean,
      default: false
    },
    generateCode: {
      type: Boolean,
      default: false
    },
    generateJson: {
      type: Boolean,
      default: false
    },
    upload: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    basicFields: {
      type: Array,
      default: () => ['input', 'textarea', 'number', 'radio', 'checkbox', 'time', 'date', 'rate', 'color', 'select', 'switch', 'slider', 'text', 'title', 'divider']
    },
    advanceFields: {
      type: Array,
      default: () => ['blank', 'imgupload', 'chart', 'report', 'button', 'editor', 'cascader']
    },
    layoutFields: {
      type: Array,
      default: () => ['grid']
    }
  },
  data() {
    return {
      basicComponents,
      layoutComponents,
      advanceComponents,
      resetJson: false,
      widgetForm: {
        list: [],
        config: {
          labelWidth: 120,
          labelPosition: 'right',
          size: 'small'
        }
      },
      viewDesign: {
        viewDesignId: null,
        businessId: null,
        groupId: null,
        viewName: null,
        viewKey: null,
        viewOption: null,
        screenCapture: null,
        isEdit: null,
        description: null
      },
      rules: {
        viewName: [{ required: true, message: '请填写页面名称', trigger: 'blur' }]
      },
      configTab: 'widget',
      widgetFormSelect: null,
      previewVisible: false,
      jsonVisible: false,
      codeVisible: false,
      uploadVisible: false,
      widgetModels: {},
      blank: '',
      htmlTemplate: '',
      vueTemplate: '',
      jsonTemplate: '',
      uploadEditor: null,
      jsonCopyValue: '',
      jsonClipboard: null,
      jsonEg: `{
  "list": [],
  "config": {
    "labelWidth": 100,
    "labelPosition": "top",
    "size": "small"
  }
}`,
      codeActiveName: 'vue',
      isCopy: null,
      saveDialogVisible: false,
      formLabelWidth: '120px'
    }
  },
  watch: {
    widgetForm: {
      deep: true,
      handler: function(val) {
        // console.log(this.$refs.widgetForm)
      }
    }
  },
  created() {
    this.viewDesign.viewDesignId = this.$route.params.viewDesignId
    const isCopy = this.$route.params.isCopy
    if (this.viewDesign.viewDesignId) {
      this.isCopy = parseInt(isCopy)
      this.get()
    }
  },
  methods: {
    get() {
      const params = { id: this.viewDesign.viewDesignId }
      get(params).then(response => {
        this.viewDesign = response.data
        this.viewDesignCopy = response.data
        this.setJSON(JSON.parse(this.viewDesign.viewOption))
      })
    },
    handleConfigSelect(value) {
      this.configTab = value
    },
    handleMoveEnd(evt) {
      console.log('end', evt)
    },
    handleMoveStart({ oldIndex }) {
      console.log('start', oldIndex, this.basicComponents)
    },
    handleMove() {
      return true
    },
    handlePreview() {
      console.log(this.widgetForm)
      this.previewVisible = true
    },
    handleTest() {
      this.$refs.generateForm.getData().then(data => {
        this.$alert(data, '').catch(e => {})
        this.$refs.widgetPreview.end()
      }).catch(e => {
        this.$refs.widgetPreview.end()
      })
    },
    handleReset() {
      this.$refs.generateForm.reset()
    },
    handleUpload() {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.uploadEditor = ace.edit('uploadeditor')
        this.uploadEditor.session.setMode('ace/mode/json')
      })
    },
    handleGenerateJson() {
      this.jsonVisible = true
      this.jsonTemplate = this.widgetForm
      console.log(JSON.stringify(this.widgetForm))
      this.$nextTick(() => {
        const editor = ace.edit('jsoneditor')
        editor.session.setMode('ace/mode/json')

        if (!this.jsonClipboard) {
          this.jsonClipboard = new Clipboard('.json-btn')
          this.jsonClipboard.on('success', (e) => {
            this.$message.success('复制成功！')
          })
        }
        this.jsonCopyValue = JSON.stringify(this.widgetForm)
      })
    },
    handleGenerateCode() {
      this.codeVisible = true
      this.htmlTemplate = generateCode(JSON.stringify(this.widgetForm), 'html')
      this.vueTemplate = generateCode(JSON.stringify(this.widgetForm), 'vue')
      this.$nextTick(() => {
        const editor = ace.edit('codeeditor')
        editor.session.setMode('ace/mode/html')

        const vueeditor = ace.edit('vuecodeeditor')
        vueeditor.session.setMode('ace/mode/html')
      })
    },
    handleUploadJson() {
      try {
        this.setJSON(JSON.parse(this.uploadEditor.getValue()))
        this.uploadVisible = false
      } catch (e) {
        this.$message.error(e.message)
        this.$refs.uploadJson.end()
      }
    },
    handleClear() {
      this.widgetForm = {
        list: [],
        config: {
          labelWidth: 100,
          labelPosition: 'right',
          size: 'small',
          customClass: ''
        }
      }

      this.widgetFormSelect = {}
    },
    handleBack() {
      this.$router.push({ name: 'ViewDesign' })
    },
    handleSave() {
      this.saveDialogVisible = true
      if (this.$refs['viewDesignForm'] !== undefined) {
        this.$refs['viewDesignForm'].clearValidate()
      }
    },
    handleSubmit() {
      this.$refs['viewDesignForm'].validate((valid) => {
        if (valid) {
          var viewContainer = document.getElementById('view-container')
          const _this = this
          const generateScreenCapture = new Promise(function(resolve) {
            _this.$message({
              type: 'info',
              message: '正在生成缩略图！'
            })
            const params = {
              useCORS: true,
              logging: false,
              width: viewContainer.clientWidth,
              height: viewContainer.clientHeight
            }
            window.html2canvas(viewContainer,
              params).then(function(canvas) {
              _this.viewDesign.screenCaptureBase64 = canvas.toDataURL('image/png')
              resolve()
            })
          })
          generateScreenCapture.then(function() {
            if (this.isCopy === 1) {
              // 证明是复制该模板，创建新的实例
              // 需要将ID置为null
              this.viewDesign.viewDesignId = null
            }
            this.viewDesign.viewOption = JSON.stringify(_this.widgetForm)
            if (this.viewDesign.viewDesignId && this.viewDesign.viewDesignId !== 'null') {
              update(this.viewDesign).then(() => {
                // 编辑
                this.$message({
                  type: 'success',
                  message: '更新成功！'
                })
                // 重新获取数据
                this.saveDialogVisible = false
                this.isCopy = 0
                this.get(this.viewDesign.viewDesignId)
              })
            } else {
              save(this.viewDesign).then(response => {
                const viewDesignId = response.data
                this.$message({
                  type: 'success',
                  message: '保存成功！'
                })
                this.saveDialogVisible = false
                // 新建会返回ID
                // 访问编辑页面
                this.$router.push({
                  name: 'ViewEdit', params:
                    {
                      viewDesignId: viewDesignId,
                      isCopy: 0
                    }
                })
                // 重新获取数据
                this.viewDesign.viewDesignId = viewDesignId
                this.isCopy = 0
                this.get(viewDesignId)
              })
            }
          }.bind(this))
        } else {
          this.$message.error('请保证数据填写正确！')
        }
      })
    },
    getJSON() {
      return this.widgetForm
    },
    getHtml() {
      return generateCode(JSON.stringify(this.widgetForm))
    },
    setJSON(json) {
      this.widgetForm = json

      if (json.list.length > 0) {
        this.widgetFormSelect = json.list[0]
      }
    },
    handleInput(val) {
      console.log(val)
      this.blank = val
    },
    handleDataChange(field, value, data) {
      console.log(field, value, data)
    }
  }
}
</script>

<style lang="scss">
.widget-empty{
  background-position: 50%;
}
</style>
